package com.taotao.order.service.ipml;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.taotao.common.pojo.TaotaoResult;
import com.taotao.domain.Order;
import com.taotao.mapper.TbOrderItemMapper;
import com.taotao.mapper.TbOrderMapper;
import com.taotao.mapper.TbOrderShippingMapper;
import com.taotao.order.dao.IJedisClient;
import com.taotao.order.service.IOrderService;
import com.taotao.pojo.TbOrder;
import com.taotao.pojo.TbOrderExample;
import com.taotao.pojo.TbOrderItem;
import com.taotao.pojo.TbOrderItemExample;
import com.taotao.pojo.TbOrderItemExample.Criteria;
import com.taotao.pojo.TbOrderShipping;
import com.taotao.pojo.TbOrderShippingExample;

/**
 * 订单 服务层*
 * 
 * @author Administrator
 *
 */
@Service
public class OrderServiceIpml implements IOrderService {
	@Autowired
	private TbOrderMapper orderMapper;

	@Autowired
	private TbOrderItemMapper orderItemMapper;

	@Autowired
	private TbOrderShippingMapper orderShippingMapper;

	@Autowired
	private IJedisClient jedisClient;

	@Value("${ORDER_GEN_KEY}")
	private String ORDER_GEN_KEY;

	@Value("${ORDER_INIT_ID}")
	private String ORDER_INIT_ID;

	@Value("${ORDER_DETAIL_GEN_KEY}")
	private String ORDER_DETAIL_GEN_KEY;

	/**
	 * 添加订单
	 */
	@Override
	public TaotaoResult createOrder(TbOrder order, List<TbOrderItem> orderItem, TbOrderShipping orderShipping) {
		// TODO Auto-generated method stub
		// 获取商品id
		String str = this.jedisClient.get(ORDER_GEN_KEY);
		if (StringUtils.isBlank(str)) {
			jedisClient.set(ORDER_GEN_KEY, ORDER_INIT_ID);
		}
		Long orderId = jedisClient.incr(ORDER_GEN_KEY);
		// 完善订单信息
		// 支付类型，1、在线支付，2、货到付款
		order.setPaymentType(1);
		// 状态：1、未付款，2、已付款，3、未发货，4、已发货，5、交易成功，6、交易关闭
		order.setStatus(1);
		Date date = new Date();
		// 订单创建时间
		order.setCreateTime(date);
		// 订单更新时间
		order.setUpdateTime(date);
		// 0：未评价 1：已评价
		order.setBuyerRate(0);

		// 设置订单id
		order.setOrderId(orderId + "");
		// 保存订单信息
		this.orderMapper.insert(order);
		// 补全商品信息
		for (TbOrderItem tbOrderItem : orderItem) {
			// 设置订单id
			tbOrderItem.setOrderId(orderId + "");
			// 生成订单商品id
			long id = jedisClient.incr(ORDER_DETAIL_GEN_KEY);
			tbOrderItem.setId(id + "");
			// 保存订单商品信息
			this.orderItemMapper.insert(tbOrderItem);
		}
		// 设置订单id
		orderShipping.setOrderId(orderId + "");
		// 时间设置
		orderShipping.setCreated(date);
		orderShipping.setUpdated(date);
		this.orderShippingMapper.insert(orderShipping);
		// 保存订单物流信息
		return TaotaoResult.ok(orderId);
	}

	/**
	 * 根据订单信息查询商品信息
	 */
	@Override
	public TaotaoResult getOrderItemByOrderId(String orderId) {
		// TODO Auto-generated method stub
		// 查询订单信息
		TbOrder _order;
		try {
			_order = this.orderMapper.selectByPrimaryKey(orderId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return TaotaoResult.build(400, "查询订单信息出错");
		}
		Order order = new Order();
		// // 填充信息
		// "orderId":"100544",
		// "payment": 5288,
		// "paymentType":1
		// "status":1
		// "createTime":"2015-01-01 08:22:14"
		// "postFee": 0,
		// "userId": "3",
		// "buyerMessage": null,
		// "buyerNick": "zhang12
		order.setOrderId(_order.getOrderId());
		order.setPayment(_order.getPayment());
		order.setPaymentType(_order.getPaymentType());
		order.setStatus(_order.getStatus());
		order.setCreateTime(_order.getCreateTime());
		order.setPostFee(_order.getPostFee());
		order.setUserId(_order.getUserId());
		order.setBuyerMessage(_order.getBuyerMessage());
		order.setBuyerNick(_order.getBuyerNick());
		TbOrderItemExample itemExample = new TbOrderItemExample();
		// 根据订单id查询商品信息
		Criteria criteria = itemExample.createCriteria();
		criteria.andOrderIdEqualTo(orderId);
		// 查找订单商品信息
		try {
			List<TbOrderItem> orderItems = this.orderItemMapper.selectByExample(itemExample);
			order.setOrderItems(orderItems);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return TaotaoResult.build(400, "查询订单商品信息出错");
		}
		// 查找订单物流信息
		// 根据订单id查询物流信息
		TbOrderShippingExample shopingExample = new TbOrderShippingExample();
		com.taotao.pojo.TbOrderShippingExample.Criteria shopingCriteria = shopingExample.createCriteria();
		shopingCriteria.andOrderIdEqualTo(orderId);
		List<TbOrderShipping> orderShippings;
		try {
			orderShippings = this.orderShippingMapper.selectByExample(shopingExample);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return TaotaoResult.build(400, "查询商品物流信息出错");
		}
		if (null != orderShippings && !orderShippings.isEmpty()) {
			TbOrderShipping orderShipping = orderShippings.get(0);
			order.setOrderShipping(orderShipping);
		}
		return TaotaoResult.ok(order);
	}

	/**
	 * 3 根据用户分页查询订单
	 */
	@Override
	public TaotaoResult getOrderItemByUserIdWithPage(Long userId, Integer page, Integer rows) {
		// TODO Auto-generated method stub
		// 通过用户查询订单信息
		TbOrderExample example = new TbOrderExample();
		com.taotao.pojo.TbOrderExample.Criteria criteria = example.createCriteria();
		criteria.andUserIdEqualTo(userId);
		// 进行分页
		List<TbOrder> orders;
		try {
			PageHelper.startPage(page, rows);
			orders = this.orderMapper.selectByExample(example);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return TaotaoResult.build(400, "查询商品信息失败");
		}
		return TaotaoResult.ok(orders);
	}

	/**
	 * 修改订单的状态
	 */
	public TaotaoResult changeStatus(String orderId, Integer status, Long paymentTime) {
		// 通过主键查询订单信息
		TbOrder order;
		try {
			order = this.orderMapper.selectByPrimaryKey(orderId);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return TaotaoResult.build(400, "查询订单信息出错");
		}
		// 改变订单的状态
		order.setStatus(status);
		// 更改修改时间
		if (paymentTime == null) {
			order.setUpdateTime(new Date());
		} else {
			order.setUpdateTime(new Date(paymentTime));
		}
		// 修改数据
		try {
			this.orderMapper.updateByPrimaryKey(order);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return TaotaoResult.build(400, "修改订单信息出错");
		}

		return TaotaoResult.ok();

	}

}
